package com.ossean.projectmanager.syncmatchresult;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.ossean.projectmanager.lasttabledao.RelativeMemoDao;
import com.ossean.projectmanager.lasttabledao.RelativeMemoToOpenSourceProjectDao;
import com.ossean.projectmanager.model.Configure;
import com.ossean.projectmanager.model.RelativeMemo;
import com.ossean.projectmanager.model.RelativeMemoToOpenSourceProject;

@Component("syncMatchResult")
public class SyncMatchResult {
	@Resource
	private RelativeMemoDao lastMemoDao;

	@Resource
	private RelativeMemoToOpenSourceProjectDao matchResultDao;

	Logger logger = Logger.getLogger(this.getClass());
	private Configure conf;

	/**
	 * 从帖子表中同步帖子信息到匹配结果表
	 * 
	 * @throws InterruptedException
	 */
	public void syncMatchResult() {
		conf = new Configure("configure");
		int startTableId = conf.getStartTableId();
		int endTableId = conf.getEndTableId();
		while(true){
			logger.info("start match table~");
			for (int i = startTableId; i <= endTableId; i++) {
				String matchResultTableName = "relative_memo_to_open_source_projects_" + String.valueOf(i);
				logger.info("starting sync " + matchResultTableName + "......");
				List<RelativeMemoToOpenSourceProject> rmtospList = matchResultDao.getMatchResultsByHassync(matchResultTableName, 50000);
				long startCircle = System.currentTimeMillis();
				while(rmtospList !=null && rmtospList.size() > 0){
					for (RelativeMemoToOpenSourceProject rmtosp : rmtospList) {
						int curMemoId = rmtosp.getRelative_memo_id();
						RelativeMemo curMemo = lastMemoDao.getById(curMemoId);
						rmtosp.setCreated_time(curMemo.getCreated_time());
						rmtosp.setMemo_type(curMemo.getMemo_type());
						rmtosp.setReplies_num(curMemo.getReplies_num());
						rmtosp.setView_num_crawled(curMemo.getView_num());
						matchResultDao.syncMatchResult(matchResultTableName, rmtosp);
						
					}
					logger.info("updated " + rmtospList.get(rmtospList.size()-1).getId() + "......");
					rmtospList =  matchResultDao.getMatchResultsByHassync(matchResultTableName, 50000);
				}
				long endCircle = System.currentTimeMillis();
				logger.info(matchResultTableName+" sync stop cost : " + (endCircle - startCircle)/6000 +" s");
			}
			logger.info("all match table have sync over!!!!");
			logger.info("......sleeping 15 min......");
			try {
				Thread.sleep(1000*60*15);// 筛选完成，休息15分钟
			} catch (InterruptedException e) {
				logger.error(e);
			}
		}
			
	}

}
